#include "Com_Mod.h"
#include <Windows.h>
#include <iostream>

using namespace std;

int Communicator::Setup(QString CurrentCom){

	//Create new serial port with io stream
	port =  new boost::asio::serial_port(io);

	if(!port->is_open()){

		try{
			port->open(CurrentCom.toLocal8Bit().constData());
			// Base serial settings
			serial_port_base::baud_rate BAUD(9600);
			serial_port_base::character_size CSIZE(8);
			serial_port_base::flow_control FLOW( serial_port_base::flow_control::none );
			serial_port_base::parity PARITY( serial_port_base::parity::none );
			serial_port_base::stop_bits STOP( serial_port_base::stop_bits::one );

			// Setup port - base settings
			port->set_option( BAUD );
			port->set_option( CSIZE );
			port->set_option( FLOW );
			port->set_option( PARITY );
			port->set_option( STOP );

			SendData.Struc.Fire = 0;

			return 0;
		} 
		catch( boost::system::system_error e ){
			return 1;
		};

	};
	return 0;

};

void Communicator::Send(int X, int Y, int AngleX, int AngleY, int Fire){
	SendData.Struc.Y = Y;
	SendData.Struc.X = X;
	SendData.Struc.AngleY = AngleY;
	SendData.Struc.AngleX = AngleX;
	SendData.Struc.Fire = Fire;

	for(int i=0; i < sizeof(SendData); i++){
		write(*port,buffer((unsigned char*)&SendData.bytes[i], 1));
	};
};

void Communicator::Recieve(){
	RecvData.Struc.Y = 0;
	RecvData.Struc.X = 0;
	RecvData.Struc.AngleY = 0;
	RecvData.Struc.AngleX = 0;
	RecvData.Struc.Fire = 0;

	for(int i=0; i < sizeof(RecvData); i++){
		if (read(*port,buffer((unsigned char*)&RecvData.bytes[i], 1)) == 0)
		{
			break;
		}
	};
};

void Communicator::run(){
	//Setup();
	Sleep(1000);
	Y = 0;
	X = 0;
	Fire = 0;

	while(1){

		//Wait until the NewData event has been fired.
		WaitForSingleObject(NewData, INFINITE);

		Send(X, Y, X, Y, Fire);
		Recieve();

		//Data has been proccesed and the NewData even will be reset.
		//The CommDone event will be fired to signal that the thread is ready for new data.
		ResetEvent(NewData);
		SetEvent(CommDone);
	};
};
